package com.rongc.client.freight.business.mine.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.FileUtil;
import com.rongc.client.core.utils.ImageUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.core.utils.SystemUtil;
import com.rongc.client.freight.ApiUrl;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.view.widget.CJRow.ARResponse;
import com.rongc.client.freight.base.view.widget.CJRow.CJRow;
import com.rongc.client.freight.base.view.widget.CJRow.CJRowListener;
import com.rongc.client.freight.base.view.widget.CJRow.CustomCJRowAdapter;
import com.rongc.client.freight.base.view.widget.CJRow.ViewBinder;
import com.rongc.client.freight.business.mine.buz.SettingBuz;
import com.rongc.client.freight.business.mine.model.CarDic;
import com.rongc.client.freight.business.mine.request.api.UpdateImgApi;
import com.rongc.client.freight.business.mine.request.api.VersionApi;
import com.rongc.client.freight.utils.UtilMethod;
import com.rongc.client.freight.utils.dic.IField;
import com.rongc.client.freight.utils.dic.impl.Field;
import com.rongc.client.freight.utils.dic.impl.Table;

import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by ccqx on 2017/7/17.
 */

public class SettingActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,View.OnClickListener{

    @Bind(R.id.cjrow)
    CJRow mRow;

    CustomCJRowAdapter baseAdapter;
    Table table_base;
    ARResponse response;
    ActionSheetDialog actionSheetDialog;

    String path;
    String nick;
    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;

    Response.Listener<String> respWorkersListener = new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            UtilMethod.dismissProgressDialog(SettingActivity.this);
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast(HandleCode.headerMessage);
                FileUtil.clearDir(FileUtil.getTempFile());

                baseAdapter.setFieldvalue("head",response);
                UniApplication.getInstance().getUserInfo().setHead(response);
                UniApplication.getInstance().getUserInfo().save();
                baseAdapter.notifyDataSetChanged();
            } else {
            }
        }
    };

    Response.Listener<JSONObject> respOrderListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                if(response.optInt("is_version_new") != 0){
                    ActivityUtils.jumpBrowser(SettingActivity.this,response.optString("version_url"));
                }else{
                    ActivityUtils.toast("已经是最新的版本。");
                }
            } else {
                UtilMethod.dismissProgressDialog(SettingActivity.this);
            }
        }
    };



    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(SettingActivity.this);
        }
    };

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        mRow.postDelayed(new Runnable() {
            @Override
            public void run() {
                File file = ImageUtils.makePaths2ImgFil(path);
                UtilMethod.showProgressDialog(SettingActivity.this, "正在上传...");
                UpdateImgApi p = new UpdateImgApi(respWorkersListener, errorListener, "img", file,
                        new UpdateImgApi.UpdateImgParams());
                RequestManager.getInstance().call(p);
                }
            },100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case  CarDic.ResultType.Head_TYPE:
                    path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
                    doUpload();
                    actionSheetDialog.dismiss();
                    setResult(RESULT_OK);
                    break;
                case CarDic.ResultType.Nickname_TYPE:
                    baseAdapter.setFieldvalue("nickname", UniApplication.getInstance().getUserInfo().getNickname());
                    baseAdapter.notifyDataSetChanged();
                    setResult(RESULT_OK);
                    break;
            }
        }
    }

    void showDialog(){
        actionSheetDialog = new ActionSheetDialog(this,new String[]{"选择照片"},null);
        actionSheetDialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position == 0){
                    choicePhotoWrapper();
                }
            }
        });
        actionSheetDialog.show();
    }

    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                UniApplication.getInstance().getUserInfo().clear();
                Intent intent = new Intent();
                intent.putExtra("quit",true);
                setResult(RESULT_OK,intent);
                finish();
                break;
        }
    }

    @Override
    public void initView() {
        initToolbar(R.string.setting_title);
    }

    String localverson ;

    @Override
    public void initData() {
        localverson = SystemUtil.getVersionName(SettingActivity.this)+"";
        response = SettingBuz.getMockBaseResponse();
        table_base = SettingBuz.getSettingTable(this);
        baseAdapter = new CustomCJRowAdapter(this, mRow,table_base, response);
        baseAdapter.setFieldvalue("head",UniApplication.getInstance().getUserInfo().getHead());
        baseAdapter.setFieldvalue("nickname", UniApplication.getInstance().getUserInfo().getNickname());
        baseAdapter.setFieldvalue("update",localverson);
        mRow.setAdapter(baseAdapter);

        baseAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(final View view1, Object data, int position, String from) {
                final View v = view1.findViewById(R.id.lablevalue);
                if("head".equals(from)){
                    if(StringUtils.isNotEmpty((String)data)) {
                        ((ViewGroup)view1).removeViewInLayout(v);
                        v.setVisibility(View.GONE);
//                        RelativeLayout.LayoutParams layoutparams = (RelativeLayout.LayoutParams) v
//                                .getLayoutParams();
                        RelativeLayout.LayoutParams layoutparams = new RelativeLayout.LayoutParams(
                                SystemUtil.dip2px(SettingActivity.this,40), SystemUtil.dip2px(SettingActivity.this,40));

                        ImageView seed = new ImageView(SettingActivity.this);
                        layoutparams.rightMargin = 10;
                        layoutparams.addRule(RelativeLayout.CENTER_VERTICAL);
                        layoutparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                        seed.setLayoutParams(layoutparams);
//                        seed.setTag(position);
                        seed.setId(v.getId());

                        ((ViewGroup) view1).addView(seed);
//                        seed.setImageResource(R.mipmap.universal_head_default);
                        Glide.with(UniApplication.getInstance())
                                .load(ApiUrl.getImgUrl((String)data))
                                .asBitmap()
                                .centerCrop()
                                .placeholder(R.mipmap.universal_head_default)
                                .into(new BitmapImageViewTarget((ImageView) view1.findViewById(seed.getId())) {
                                    @Override
                                    protected void setResource(Bitmap resource) {
                                        RoundedBitmapDrawable roundedBitmapDrawable =
                                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                                        roundedBitmapDrawable.setCircular(true);
//                                        roundedBitmapDrawable.setCornerRadius(20); //设置圆角半径（根据实际需求）
                                        roundedBitmapDrawable.setAntiAlias(true); //设置反走样
                                        getView().setImageDrawable(roundedBitmapDrawable);
                                    }
                                });



                    }
                    return true;
                }
                return false;
            }
        });

        baseAdapter.setCJRowListener(new CJRowListener() {
            @Override
            public boolean seedAction(int location, Field field, Object obj) {
                return false;
            }

            @Override
            public boolean activityAction(Field field, Object obj) {
                if("head".equals(field.getFieldName())){
                    showDialog();
                }else if("nickname".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(SettingActivity.this,EditActivity.class, CarDic.ResultType.Nickname_TYPE);
                }else if("password".equals(field.getFieldName())){
                    ActivityUtils.startActivity(SettingActivity.this,PasswordPayActivity.class);
                }else if("bank".equals(field.getFieldName())){
                    ActivityUtils.startActivity(SettingActivity.this,BankAddActivity.class);
                }else if("feedback".equals(field.getFieldName())){
                    ActivityUtils.startActivity(SettingActivity.this,FeedbackActivity.class);
                }else if("about".equals(field.getFieldName())){
                    ActivityUtils.startActivity(SettingActivity.this,AboutActivity.class);
                }else if("update".equals(field.getFieldName())){
                    RequestManager.getInstance().call(new VersionApi(
                            new VersionApi.VersionParams(SystemUtil.getVersionName(SettingActivity.this)+""),
                            respOrderListener, errorListener));
                }else if("clear".equals(field.getFieldName())){

                    try {
                        if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                            Glide.get(UniApplication.getInstance()).clearMemory();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    UtilMethod.showProgressDialog(SettingActivity.this);

                    mRow.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            UtilMethod.dismissProgressDialog(SettingActivity.this);
                            ActivityUtils.toast("已清除缓存");
                        }
                    },500);

                }
                return true;
            }

            @Override
            public boolean popupWindowAction(final IField field, Object obj) {
                return false;
            }
        });
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "FreDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 1, null), CarDic.ResultType.Head_TYPE);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_setting;
    }
}
